/**
* @file      serial.c
* @author    Supachai Vorapojpisut
* @version   1.0
* @date      November 30, 2014
* @brief     Serial communication module.
*/

/* Includes -----------------------------------------------------------------------*/
#include "serial.h"

/* Private constants --------------------------------------------------------------*/
#define MAX_UART_BUF_LENGTH		64

/* Private types ------------------------------------------------------------------*/
typedef struct {
    uint32_t  Tx_HeadIdx;
    uint32_t  Tx_TailIdx;
    uint8_t   Tx[MAX_UART_BUF_LENGTH];
    uint32_t  Rx_HeadIdx;
    uint32_t  Rx_TailIdx;
    uint8_t   Rx[MAX_UART_BUF_LENGTH];	
} UART_RingBuffer;

/* Private macro ------------------------------------------------------------------*/
#define __BUF_IS_FULL(headidx, tailidx)		((tailidx)==(((headidx)+1)%MAX_UART_BUF_LENGTH))
#define __BUF_IS_EMPTY(headidx, tailidx)	((headidx)==(tailidx))
#define __BUF_RESET(bufidx)					((bufidx)=0)
#define __BUF_INCR(bufidx)					((bufidx)=((bufidx)+1)%MAX_UART_BUF_LENGTH)
#define __BUF_ALLOC(headidx, tailidx)		((headidx>=tailidx)?(headidx-tailidx):(MAX_UART_BUF_LENGTH-tailidx+headidx))

/* Private variables --------------------------------------------------------------*/
static UART_RingBuffer UART_Buffer;
volatile static int UART_TxIrqState = RESET;

/* Private function prototypes ----------------------------------------------------*/
static void USART_TxIRQHandler(void);
static void USART_RxIRQHandler(void);

/* Private functions --------------------------------------------------------------*/
// Transmit IRQ Handler: move one byte from buffer to USART_DR.
static void USART_TxIRQHandler()
{
	if (!__BUF_IS_EMPTY(UART_Buffer.Tx_HeadIdx, UART_Buffer.Tx_TailIdx)) {
		USART_SendData(USART1, UART_Buffer.Tx[UART_Buffer.Tx_TailIdx]);
		__BUF_INCR(UART_Buffer.Tx_TailIdx);
	} else {
		USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
		UART_TxIrqState = RESET;
	}
}


// Receive IRQ Handler: move incoming byte from USART_DR to buffer.
static void USART_RxIRQHandler()
{
	uint8_t val;
	
	if (!__BUF_IS_FULL(UART_Buffer.Rx_HeadIdx, UART_Buffer.Rx_TailIdx)) {
		UART_Buffer.Rx[UART_Buffer.Rx_HeadIdx] = USART_ReceiveData(USART1);  
		__BUF_INCR(UART_Buffer.Rx_HeadIdx);
	} else {
		val = USART_ReceiveData(USART1); // dummy read
	}
}


// IRQ handler for USART1
void USART1_IRQHandler() 
{
	if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) {
		USART_RxIRQHandler();
	}
	if (USART_GetITStatus(USART1, USART_IT_TXE) != RESET) {
		USART_TxIRQHandler();
	}
}


/**
* @brief    Configure USART for serial communication
* @param    baud_rate   
*/
void Serial_config(uint32_t baud_rate)
{
    GPIO_InitTypeDef gpio_init_struct;
    USART_InitTypeDef usart_init_struct;
    NVIC_InitTypeDef nvic_init_struct;
    
    // Enable USART and GPIOA using RCC
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
    
    // Configure GPIOB in AF (PB6 = Tx, PB7 = Rx)
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_USART1);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_USART1);
    
    gpio_init_struct.GPIO_Mode = GPIO_Mode_AF;
    gpio_init_struct.GPIO_OType = GPIO_OType_PP;
    gpio_init_struct.GPIO_PuPd = GPIO_PuPd_UP;
    gpio_init_struct.GPIO_Speed = GPIO_Speed_2MHz;
    gpio_init_struct.GPIO_Pin = GPIO_Pin_6;
    GPIO_Init(GPIOB, &gpio_init_struct);
    
    gpio_init_struct.GPIO_Pin = GPIO_Pin_7;
    GPIO_Init(GPIOB, &gpio_init_struct);   
        
    // Configure USART for baud_rate,8,n,1
    usart_init_struct.USART_BaudRate = baud_rate;
    usart_init_struct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    usart_init_struct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    usart_init_struct.USART_WordLength = USART_WordLength_8b;
    usart_init_struct.USART_Parity = USART_Parity_No;
    usart_init_struct.USART_StopBits = USART_StopBits_1;
    USART_Init(USART1, &usart_init_struct);
    
    // Enable USART1 IRQ Handler
    nvic_init_struct.NVIC_IRQChannel = USART1_IRQn;
    nvic_init_struct.NVIC_IRQChannelPreemptionPriority = 0x00; 
    nvic_init_struct.NVIC_IRQChannelSubPriority = 0x00;
    nvic_init_struct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&nvic_init_struct);
    
    // Enable RXNE IRQ
    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
    
    // Enable USART
    USART_Cmd(USART1, ENABLE);

	// Initialize UART buffer
	__BUF_RESET(UART_Buffer.Rx_HeadIdx);
	__BUF_RESET(UART_Buffer.Rx_TailIdx);
	__BUF_RESET(UART_Buffer.Tx_HeadIdx);
	__BUF_RESET(UART_Buffer.Tx_TailIdx);
}


/**
* @brief    Read from serial port
* @retval   Read one byte from buffer
*/
uint8_t Serial_read(void)
{
    int val = -1;

	while (__BUF_IS_EMPTY(UART_Buffer.Rx_HeadIdx, UART_Buffer.Rx_TailIdx));
	USART_ITConfig(USART1, USART_IT_RXNE, DISABLE);
	val = UART_Buffer.Rx[UART_Buffer.Rx_TailIdx];
	__BUF_INCR(UART_Buffer.Rx_TailIdx);
	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);

	return val;
}


/**
* @brief    Read from serial port
* @param    Send one byte or push into buffer
*/
void Serial_write(uint8_t val)
{
	if (__BUF_IS_EMPTY(UART_Buffer.Tx_HeadIdx, UART_Buffer.Tx_TailIdx) && (UART_TxIrqState == RESET)) {
		USART_SendData(USART1, val);
		UART_TxIrqState = SET;
	} else {
		while (__BUF_IS_FULL(UART_Buffer.Tx_HeadIdx, UART_Buffer.Tx_TailIdx));
        USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
		UART_Buffer.Tx[UART_Buffer.Tx_HeadIdx] = val;
		__BUF_INCR(UART_Buffer.Tx_HeadIdx);			
	}
	USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
}


/**
* @brief    Check buffer
* @retval   Number of bytes in buffer
*/
int Serial_available(void)
{
    return __BUF_ALLOC(UART_Buffer.Rx_HeadIdx, UART_Buffer.Rx_TailIdx);
}

